package com.pd.kit;

import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by dong peng on 2018/5/1.
 */
public class SeqByRedis {

    private static String fmtDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(new Date());
    }

    /**
     * 业务流水号(唯一标示一笔业务)
     * 由业务前缀(2字符,参见SeqNumGeneration.BizEnum)+日期时间(yyyyMMddHHmmss)+流水号(6位数字)组成
     *
     * @return
     */
    public synchronized static String generateBizSeqNo(SeqByRedis.BizEnum constant){
        String dateStr = fmtDate();
        Jedis jedis = null;
        Long count = null;
        String key = "SeqByRedis.generateBizSeqNo";
        try {
            jedis = JedisPoolUtil.getInstance();
            count = jedis.incr(key);
            if(count > 999999) {
                jedis.del(key);
            }
        }finally {
            if (jedis != null) {
                jedis.close();
            }
        }

        String tmp = String.valueOf(count);
        while (tmp.length() <= 6) {
            tmp = "0"+tmp;
        }
        return constant.name() + dateStr + tmp;
    }


    public enum  BizEnum {
        CM; // 代表本系统
    }

}
